<template>
  <div class="login">
    <el-form
      ref="loginForm"
      :model="loginForm"
      :rules="loginRules"
      class="login-form right-bottom"
      v-show="!forgetPassword"
    >

      <!-- 二维码登录 -->
      <div v-show="!codeLogin" style="display:flex;justify-content: center;margin-top:-20px">
        <div class="top-right" @click="toPasswordLogin">
          <img src="../assets/image/computer.png" style="width:100%" />
        </div>
        <div class="codeLoginBox">
          <!-- <img src="../assets/image/co-wx-text.png" alt /> -->
          <!-- style="width:248px;height:248px;border:1px solid red" -->
          <!-- <div> -->
            <div class="qr_login" id="wx_reg"></div>
          <!-- </div> -->
          <!-- <div class="co-wx-text">请使用企业微信扫描二维码登录 “xxx”</div> -->
        </div>
      </div>
      <!-- 密码登录 -->
      <div v-show="codeLogin">
        <div class="top-right" @click="toCodeLogin">
          <img src="../assets/image/erweima.png" style="width:100%" />
        </div>
        <!-- 企业微信账号绑定 -->
        <div v-show="wwBind">
          <h3 class="title">企业微信账号绑定</h3>
          <el-form-item prop="username" label="账号">
            <el-input v-model="username" type="text" auto-complete="off" placeholder="账号"></el-input>
          </el-form-item>
          <el-form-item prop="password" label="密码">
            <el-input v-model="password" type="password" auto-complete="off" placeholder="密码"></el-input>
          </el-form-item>
          <el-form-item style="width:100%;">
            <el-button
              :loading="loading"
              size="medium"
              type="primary"
              style="width:100%;"
              @click.native.prevent="wwloginBind"
            >绑定</el-button>
          </el-form-item>
        </div>

        <!-- 账号密码登录 -->
        <div v-show="!wwBind">
          <h3 class="title">账号登录</h3>
          <el-form-item prop="username">
            <el-input v-model="loginForm.username" type="text" auto-complete="off" placeholder="账号">
              <svg-icon slot="prefix" icon-class="user" class="el-input__icon input-icon" />
            </el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-input
              v-model="loginForm.password"
              type="password"
              auto-complete="off"
              placeholder="密码"
              @keyup.enter.native="handleLogin"
            >
              <svg-icon slot="prefix" icon-class="password" class="el-input__icon input-icon" />
            </el-input>
          </el-form-item>
          <el-form-item prop="code">
            <el-input
              v-model="loginForm.code"
              auto-complete="off"
              placeholder="验证码"
              style="width: 63%"
              @keyup.enter.native="handleLogin"
            >
              <svg-icon slot="prefix" icon-class="validCode" class="el-input__icon input-icon" />
            </el-input>
            <div class="login-code">
              <img :src="codeUrl" @click="getCode" class="login-code-img" />
            </div>
          </el-form-item>

          <el-form-item style="width:100%;">
            <el-button
              :loading="loading"
              size="medium"
              type="primary"
              style="width:100%;"
              @click.native.prevent="handleLogin"
            >
              <span v-if="!loading">登 录</span>
              <span v-else>登 录 中...</span>
            </el-button>
          </el-form-item>
          <div style="display:flex;justify-content:space-between;margin-bottom:25px">
            <el-checkbox v-model="loginForm.rememberMe">记住密码</el-checkbox>
            <span style="font-size:12px;color:gray;cursor:pointer" @click="toForgetPassword">忘记密码</span>
          </div>
        </div>
      </div>
      
    </el-form>

    <!-- 忘记密码 -->
    <el-form
      ref="passwordForm"
      :model="passwordForm"
      :rules="passwordRules"
      class="login-form"
      label-width="80px"
      v-show="forgetPassword"
      style="padding-top:10px;height:400px"
      size="mini"
    >
      <h3 class="title" style="margin:10px;">忘记密码</h3>
      <el-form-item prop="phone" label="手机号">
        <el-input
          v-model="passwordForm.phone"
          type="text"
          placeholder="请输入手机号"
          style="width:250px;"
        ></el-input>
      </el-form-item>
      <el-form-item prop="code" label="验证码">
        <el-input
          v-model="passwordForm.code"
          placeholder="请输入验证码"
          style="width:130px;margin-right:10px"
        ></el-input>
        <el-button type="primary" :loading="codeLoading" @click="getPhoneCodeFn">获取验证码</el-button>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input type="password" v-model="passwordForm.password" style="width:250px"></el-input>
      </el-form-item>
      <el-form-item label="确认密码" prop="checkPassword">
        <el-input type="password" v-model="passwordForm.checkPassword" style="width:250px"></el-input>
      </el-form-item>
      <p class="password-rule">
        1:长度为8～32位。
        <br />2:密码必须包含:大写字母、小写字母、数字、特殊
        <br />符号（!@#$%^&*0_+-=）
        <br />
      </p>
      <div class="forget-psw-foot">
        <el-form-item>
          <el-button type="primary" @click="resetForm('passwordForm')">取消</el-button>
          <el-button type="primary" @click="submitForm('passwordForm')">确定</el-button>
        </el-form-item>
      </div>
    </el-form>

    <!--  底部  -->
    <div class="el-login-footer">
      <span>Copyright © 2018-2020 mdsoftware.cn All Rights Reserved.</span>
    </div>
  </div>
</template>


<script>
import {
  getCodeImg,
  getPhoneCode,
  forgetPassword,
  wwLogin,
  wwLoginBind
} from "@/api/login";
import Cookies from "js-cookie";
import { encrypt, decrypt } from "@/utils/jsencrypt";

export default {
  name: "Login",
  data() {
    var validatePass = (passwordRules, value, callback) => {
      if (value === "") {
        callback(new Error("请输入密码"));
      } else if (
        !value.match(/^(?=.*[a-z])(?=.*[A-Z])(?=.*[1-9])(?=.*[\W]).{8,32}$/)
      ) {
        callback(
          new Error("密码必须包含大小写字母、数字、特殊符号且长度为8-32")
        );
      } else {
        if (this.passwordForm.checkPassword !== "") {
          this.$refs.passwordForm.validateField("checkPassword");
        }
        callback();
      }
    };
    var validatePass2 = (passwordRules, value, callback) => {
      if (value === "") {
        callback(new Error("请再次输入密码"));
      } else if (value !== this.passwordForm.password) {
        callback(new Error("两次输入密码不一致!"));
      } else {
        callback();
      }
    };
    var validatePhone = (passwordRules, value, callback) => {
      if (value === "") {
        callback(new Error("请输入手机号"));
      }
    };
    var validateCode = (passwordRules, value, callback) => {
      if (value === "") {
        callback(new Error("请输入验证码"));
      }
    };
    return {
      scaned:false,
      codeUrl: "",
      cookiePassword: "",
      loginForm: {
        username: "",
        password: "",
        // username: "admin",
        // password: "987!aDmin",
        rememberMe: false,
        code: "",
        uuid: ""
      },
      loginRules: {
        username: [
          { required: true, trigger: "blur", message: "用户名不能为空" }
        ],
        password: [
          { required: true, trigger: "blur", message: "密码不能为空" }
        ],
        code: [{ required: true, trigger: "change", message: "验证码不能为空" }]
      },
      loading: false,
      redirect: undefined,

      codeLogin: true,
      codeLoading: false,
      passwordForm: {
        phone: "",
        code: "",
        password: "",
        checkPassword: ""
      },
      passwordRules: {
        password: [
          { validator: validatePass, trigger: "blur", required: true }
        ],
        checkPassword: [
          { validator: validatePass2, trigger: "blur", required: true }
        ],
        phone: [{ validator: validatePhone, trigger: "blur", required: true }],
        code: [{ validator: validateCode, trigger: "blur", required: true }]
      },
      forgetPassword: false,
      wwBind: false,
      // wwlogin
      code: "",
      encryptHex: "",
      password: "",
      username: ""
    };
  },
  watch: {
    $route: {
      handler: function(route) {
        this.redirect = route.query && route.query.redirect;
        console.log(route);
      },
      immediate: true
    }
  },
  created() {
    this.getCode();
    this.getCookie();
  },
  mounted() {
    this.createWwloginCode();
    this.code = decodeURIComponent(window.location.href).split("?")[2].slice(5);
    this.wwlogin();
  },
  methods: {
    
    getCode() {
      getCodeImg().then(res => {
        this.codeUrl = "data:image/gif;base64," + res.img;
        this.loginForm.uuid = res.uuid;
      });
    },
    getCookie() {
      const username = Cookies.get("username");
      const password = Cookies.get("password");
      const rememberMe = Cookies.get("rememberMe");
      this.loginForm = {
        username: username === undefined ? this.loginForm.username : username,
        password:
          password === undefined ? this.loginForm.password : decrypt(password),
        rememberMe: rememberMe === undefined ? false : Boolean(rememberMe)
      };
    },
    handleLogin() {
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          this.loading = true;
          Cookies.set("username", this.loginForm.username, { expires: 30 });
          if (this.loginForm.rememberMe) {
            // Cookies.set("username", this.loginForm.username, { expires: 30 });
            Cookies.set("password", encrypt(this.loginForm.password), {
              expires: 30
            });
            Cookies.set("rememberMe", this.loginForm.rememberMe, {
              expires: 30
            });
          } else {
            // Cookies.remove("username");
            Cookies.remove("password");
            Cookies.remove("rememberMe");
          }
          this.$store
            .dispatch("Login", this.loginForm)
            .then(() => {
              this.$router.push({ path: this.redirect || "/" });
            })
            .catch(() => {
              this.loading = false;
              this.getCode();
            });
        }
      });
    },
    toCodeLogin() {
      this.codeLogin = false;
      this.wwBind = false;
    },
    toPasswordLogin() {
      this.codeLogin = true;
    },
    resetForm(passwordForm) {
      this.$refs[passwordForm].resetFields(); //清空
      this.forgetPassword = false;
    },
    toForgetPassword() {
      this.forgetPassword = true;
    },
    submitForm(passwordForm) {
      this.$refs[passwordForm].validate(valid => {
        if (valid) {
          alert("submit!");
        } else {
          console.log("error submit!!");
          return false;
        }
      });
      const data = {
        phone: this.passwordForm.phone,
        captcha: this.passwordForm.code,
        password: this.passwordForm.password
      };
      forgetPassword(data).then(res => {
        this.$message.success("密码修改成功");
        this.forgetPassword = false;
      });
    },
    getPhoneCodeFn() {
      const data = { phone: this.passwordForm.phone };
      getPhoneCode(data).then(res => {
        this.$message.success("已发送验证码");
      });
    },
    createWwloginCode() {
      new WwLogin({
        id: "wx_reg",
        appid: "ww39ac2af31f7fd43f",
        agentid: "1000002",
        redirect_uri: "http://gaotongliang.mdshuzhi.com",
        state: "",
        href: "",
        lang: "zh"
      });
    },
    wwlogin() {
      wwLogin({ code: this.code }).then(res => {
        if (res.data.code === 200) {
          Cookies.set("Admin-Token", res.data.token, { expires: 30 });
          this.$router.push('/index')
        }
        this.encryptHex = res.data.encryptHex;
        this.codeLogin = true;
        this.wwBind = true;
      });
    },
    wwloginBind() {
      if (!this.username) {
        this.$message.error("账号不能为空");
        return;
      }
      if (!this.password) {
        this.$message.error("密码不能为空");
        return;
      }
      const data = {
        encryptHex: this.encryptHex,
        password: this.password,
        username: this.username
      };
      wwLoginBind(data).then(res => {
        this.$message.success("账号绑定成功");
        this.wwBind = false;
      });
    }
  }
};
</script>

<style rel="stylesheet/scss" lang="scss">
.login {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  position: relative;

  background-image: url("../assets/image/loginBgi.png");
  background-size: cover;
}
.title {
  margin: 0px auto 30px auto;
  text-align: center;
  color: #707070;
}

.login-form {
  // border-radius: 6px;
  background-color: #fff;
  width: 400px;
  height: 365px;
  padding: 25px 25px 5px 25px;
  position: absolute;
  // background-image: linear-gradient(#cee4f6, #d0dcf7);
  .el-input {
    height: 38px;
    input {
      height: 38px;
    }
  }
  .input-icon {
    height: 39px;
    width: 14px;
    margin-left: 2px;
  }
}
.right-bottom {
  right: 60px;
  bottom: 60px;
}
.login-tip {
  font-size: 13px;
  text-align: center;
  color: #bfbfbf;
}
.login-code {
  width: 33%;
  height: 38px;
  float: right;
  img {
    cursor: pointer;
    vertical-align: middle;
  }
}
.el-login-footer {
  height: 40px;
  line-height: 40px;
  position: fixed;
  bottom: 0;
  width: 100%;
  text-align: center;
  color: #fff;
  font-family: Arial;
  font-size: 12px;
  letter-spacing: 1px;
}
.login-code-img {
  height: 38px;
}
.top-right {
  // border: 1px solid red;
  width: 60px;
  height: 60px;
  position: absolute;
  right: 5px;
  top: 5px;
  cursor: pointer;
}
.codeLoginBox {
  
  .qr_login{
    transform: scale(0.85) !important;
  // background-color: red;
  // width: 250px;height: 250px;
}
}
.co-wx-text {
  margin-top: 5px;
  font-size: 14px;
  font-family: PingFangSC-Medium, PingFang SC;
  font-weight: 500;
  color: #909399;
  line-height: 20px;
}
.password-rule {
  font-size: 12px;
  font-family: PingFangSC-Regular, PingFang SC;
  font-weight: 400;
  color: #909399;
  line-height: 17px;
}
.forget-psw-foot {
  display: flex;
  justify-content: flex-end;
  border-top: 1px solid #f1f1f1;
  padding-top: 10px;
}

</style>
